package com.websocket;

import java.io.IOException;
import java.util.ArrayList;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import com.alibaba.fastjson.JSONObject;
import com.pojo.Info;
import com.pojo.User;
import com.service.IInfoService;
import com.service.IUserService;

public class ChatMessageHandler extends TextWebSocketHandler {

	private static final ArrayList<WebSocketSession> users;
	private static Logger logger = Logger.getLogger(ChatMessageHandler.class);
	private JSONObject json;
	@Resource
	private IInfoService infoService;
	@Resource
	private Info info;
	@Resource
	private IUserService userService;

	static {
		users = new ArrayList<WebSocketSession>();
	}

	/**
	 * 连接成功时候，会触发UI上onopen方法
	 * 
	 * @param session
	 *            当前用户的session
	 */
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		users.add(session);
	}

	/**
	 * 在UI在用js调用websocket.send()时候，会调用该方法
	 */
	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		json = JSONObject.parseObject(message.getPayload());
		info.setContent(json.getString("content"));
		info.setTime(json.getString("time"));
		info.setTitle(json.getString("title"));
		User user = userService.findByUsername(json.getString("name"));
		infoService.addinfo(info, user.getId());

		sendMessageToUsers(message);
	}

	/**
	 * 给某个用户发送消息
	 *
	 * @param userName
	 * @param message
	 */
	public void sendMessageToUser(String userName, TextMessage message) {
		for (WebSocketSession user : users) {
			if (user.getAttributes().get(Constants.WEBSOCKET_USERNAME).equals(userName)) {
				try {
					if (user.isOpen()) {
						user.sendMessage(message);
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
				break;
			}
		}
	}

	/**
	 * 给所有在线用户发送消息
	 *
	 * @param message
	 */
	public void sendMessageToUsers(TextMessage message) {
		for (WebSocketSession user : users) {
			try {
				if (user.isOpen()) {
					user.sendMessage(message);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		if (session.isOpen()) {
			session.close();
		}
		logger.debug("websocket connection closed......");
		users.remove(session);
	}

	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		logger.debug("websocket connection closed......");
		users.remove(session);
	}

	@Override
	public boolean supportsPartialMessages() {
		return false;
	}

}
